package cn.itsource._01_rabbitmq_helloword;

import cn.itsource.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

import static cn.itsource._01_rabbitmq_helloword.send.QUEUE_NAME;

//消息接收者
public class rev {
    public static void main(String[] args) throws Exception {
        //获得连接对象
        Connection connection = ConnectionUtil.getConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);
        /**
         * 消费者接收消息调用此方法
         * @param consumerTag 消费者的标签，在channel.basicConsume()去指定
         * @param envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志
        (收到消息失败后是否需要重新发送)
         * @param properties
         * @param body
         **/
        Consumer consume=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //消息的内容
                System.out.println(new String(body,"utf-8"));
                System.out.println("id:"+envelope.getDeliveryTag());
                System.out.println("队列名称:"+envelope.getRoutingKey());
                System.out.println("交换机:"+envelope.getExchange());

            //手动签收 long deliveryTag 消息的id, boolean multiple 是否等所有的消息都接收完再签收

            channel.basicAck(envelope.getDeliveryTag(),true);

            }
        };
        //接收消息
        //String basicConsume(String queue, DeliverCallback deliverCallback 接收方式, CancelCallback cancelCallback)
        channel.basicConsume(QUEUE_NAME,false,consume);
    }
}
